<template>
  <div class="dialog_content">
    <el-dialog class="m_dialog" :title="dialogTitles[titleIndex] || titleIndex" :visible.sync="dialogVisible" append-to-body :before-close="cancel" :close-on-click-modal="false">
      <div class="head">
        <el-row class="flex serach_item">
          <el-button type="primary" :class="setActive(0)" @click="changeDeviceForm(0)">设备信息</el-button>
          <el-button type="primary" :class="setActive(1)" @click="changeDeviceForm(1)">参数设置</el-button>
          <el-button type="primary" :class="setActive(2)" @click="changeDeviceForm(2)">平面图位置</el-button>
        </el-row>
      </div>
      <div class="content">
        <DeviceInfo :titleIndex="titleIndex" ref="deviceInfo" v-show="btnActive == 0" :formData="formModel" :dictMap="dictMap" :deviceClassList="deviceClassList" :ProjectPointPicList="ProjectPointPicList" @getPictrue="getPictrue"></DeviceInfo>
        <ParamsSetttings ref="paramsSetttings" v-show="btnActive == 1" :formData="formModel" :dictMap="dictMap"></ParamsSetttings>
        <PlanPosition ref="planPosition" v-show="btnActive == 2" :formData="formModel" :pictrue="pictrue" :key="Math.random()"></PlanPosition>

      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel" class="btn_cancel">取 消</el-button>
        <el-button type="primary" @click="submitFrom" class="btn_primary">保 存</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>

import { getProjectPointControl } from '@/api/projectPoints'
import { getProjectPointPicList } from '@/api/projectPoints/projectImg'
import DeviceInfo from './management/DeviceInfo';
import ParamsSetttings from './management/ParamsSetttings';
import PlanPosition from '@/components/SetPoints';
import ManagementFormBaseInfo from './ManagementFormBaseInfo.vue';
import { addDeviceData, updateDeviceData } from '@/api/system/device/management';
import { mapState } from 'vuex';
export default {
  name: 'ManagementForm',
  props: {
    dialogVisible: {
      type: Boolean,
      default: false
    },
    titleIndex: {
      type: Number | String,
      default: 0,
    },
    formData: {
      type: Object,
      default: () => { },
    },
    dictMap: {
      type: Object,
      default: () => { },
    },
    deviceClassList: {
      type: Array,
      default: () => [],
    },
    tabActive: {
      type: Number,
      default: 0,
    }
  },
  data() {
    return {
      // 平面图对象(给平面图位置页面使用)
      pictrue: {},
      isSubmitDeviceInfo: false,
      // 提交表单数据
      formModel: {},
      // 按钮切换数据
      btnActive: 0,
      // 项目点图片列表
      ProjectPointPicList: []
    };
  },
  computed: {
    ...mapState('dialog', ['dialogTitles']),
    ...mapState('config', ['inFilePrefix'])
  },
  watch: {
    formData: {
      deep: true,
      immediate: true,
      handler() {
        for (let p in this.formData) {
          let item = this.formData[p]
          if (item !== undefined) {
            // if(p == "buyTime" || p == "enableTime" || p == "validTime"){
            //   item = item.split("T")[0] + " " + item.split("T")[1].split(".")[0]
            // }
            // this.formModel[p] = item
            this.$set(this.formModel, p, item)
          } else {
            // this.formModel[p] = ''
            this.$set(this.formModel, p, '')
          }
        }
      },
    },
    dialogVisible: {
      handler() {
        if (this.dialogVisible) {
          this.toGetProjectPointPicList()
          this.toGetProjectPointControl()
        }
      },
    },
    tabActive: {
      handler() {
        this.btnActive = this.tabActive
      }
    },
  },
  created() { },
  mounted() { },
  methods: {
    getList() {
      this.$emit('getList');
    },
    cancel() {
      this.$emit('cancel');
      this.$refs["deviceInfo"].getForm().toResetFields();
      this.$refs["paramsSetttings"].getForm().toResetFields();
    },
    submitFrom() {

      let formModel_deviceInfo = this.$refs.deviceInfo.formModel,
        formModel_paramsSetttings = this.$refs.paramsSetttings.formModel,
        formModel_planPosition = this.$refs.planPosition.formModel;

      let formdata = { ...formModel_deviceInfo, ...formModel_paramsSetttings, ...formModel_planPosition }

      let promiseSet = (type) => {
        return new Promise((resolve, reject) => {
          this.$refs[type].getForm().validate((valid, item) => {
            if (valid) {
              resolve(type)
            } else {
              reject(type)
            }
          })
        })
      }

      Promise.all([promiseSet('deviceInfo'), promiseSet('paramsSetttings')]).then((type) => {
        if (formdata.deviceId) {
          updateDeviceData(formdata).then(res => {
            if (res && 200 === res.code) {
              this.$message({
                message: '修改成功',
                type: 'success',
              });
              this.cancel();
              this.getList();
            }
          });
        } else {
          addDeviceData(formdata).then(res => {
            if (res && 200 === res.code) {
              this.$message({
                message: '添加成功',
                type: 'success',
              });
              this.cancel();
              this.getList();
            }
          });
        }
      }).catch((type) => {
        if (type == 'deviceInfo') {
          this.changeDeviceForm(0)
        } else if (type == 'paramsSetttings') {
          this.changeDeviceForm(1)
        } else {
          this.changeDeviceForm(2)
        }
      })
    },
    // 切换内容
    changeDeviceForm(cur) {
      this.btnActive = cur
      this.$emit("setTabActive", cur)
    },
    // 切换按钮样式设置
    setActive(type) {
      return this.btnActive == type ? 'btn_group_active' : 'btn_group'
    },
    // 获取平面图对象数据
    getPictrue(pictrue) {
      if (this.$utils.isNotEmpty(pictrue)) {
        this.pictrue = pictrue
        if (!this.formModel.projectPointPicId) {
          this.pictrue.positionX = 0
          this.pictrue.positionY = 0
        }
      }
    },
    // 获取项目点图片列表
    toGetProjectPointPicList() {
      getProjectPointPicList({
        picType: 1,
        projectPointId: this.formModel.projectPointId
      }).then((res) => {
        this.ProjectPointPicList = res.rows

        this.toSetProjectPointPic()
      })
    },
    // 设置平面图对象数据
    toSetProjectPointPic() {
      this.ProjectPointPicList = this.ProjectPointPicList.map(item => {
        item.picUrl = this.inFilePrefix + item.picUrl
        return item
      })
      let arr = this.ProjectPointPicList.filter(item => item.projectPointPicId == this.formModel.projectPointPicId)
      if (arr.length) {
        let item = arr[0]
        this.pictrue = item

      } else {
        this.pictrue = {}
      }
    },
    // 获取设备所在项目点
    toGetProjectPointControl() {
      getProjectPointControl(this.formModel.projectPointId).then(res => {
        if (res && 200 == res.code) {
          this.$set(this.formModel, 'projectPointName', res.data.projectPointName)
        }
      })
    }
  },
  components: {
    ManagementFormBaseInfo,
    DeviceInfo,
    ParamsSetttings,
    PlanPosition,
  },
};
</script>

<style lang="less" scoped></style>
